package org.dubh.dp;

import com.google.common.collect.Lists;

import java.util.Collection;

import static org.junit.Assert.assertEquals;
import org.junit.Test;


public class KnapsackTests {
    @Test
    public void shouldSolveSimpleProblem() {
        Knapsack sack = new Knapsack( 15 );

        Collection<KnapsackItemType> items = sack.optimizeContents(Lists.immutableList( 
            new KnapsackItemType( 4, 12, "Green" ),
            new KnapsackItemType( 2, 2, "Blue" ),
            new KnapsackItemType( 1, 1, "Red" ),
            new KnapsackItemType( 10, 4, "Yellow" ),
            new KnapsackItemType( 2, 1, "Gray" )
        ));
        printItems( items );

        assertEquals( 15, costSum( items ) );
        assertEquals( 36, valueSum( items ) );    
    }
    
    private void printItems( Collection<KnapsackItemType> items ) {
        StringBuilder sb = new StringBuilder();
        for ( KnapsackItemType item : items ) {
            sb.append( item.description() );
            sb.append( ", " );
        }
        if ( items.size() > 0 ) sb.setLength( sb.length() - 2 );
        System.err.println( sb.toString() );
    }
    
    private int valueSum( Collection<KnapsackItemType> items ) {
        int sum = 0;
        for ( KnapsackItemType item : items ) {
            sum += item.value();
        }
        return sum;
    }
    
    private int costSum( Collection<KnapsackItemType> items ) {
        int sum = 0;
        for ( KnapsackItemType item : items ) {
            sum += item.cost();
        }
        return sum;
    }
    
    @Test
    public void shouldFailWithZeroKnapsack() {
        new Knapsack( 0 );
    }
}
